package com.chenxin.wms.process.task.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chenxin.common.constant.WmsConstants;
import com.chenxin.common.core.domain.ProcResult;
import com.chenxin.common.exception.wms.WmsException;
import com.chenxin.common.utils.StringUtils;
import com.chenxin.common.utils.uuid.Seq;
import com.chenxin.wms.domain.WcsTaskEntity;
import com.chenxin.wms.domain.dto.SendTaskToWcsParams;
import com.chenxin.wms.mapper.WcsTaskMapper;
import com.chenxin.wms.process.task.IProcSendTaskToWcs;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProcSendTaskToWcsImpl implements IProcSendTaskToWcs {
    @Autowired
    private WcsTaskMapper wcsTaskMapper;

    @Override
    public ProcResult call(SendTaskToWcsParams params) {
        if (params == null) {
            throw new WmsException("send_wcs_error_001", "参数不能为空");
        }
        // 托盘条码
        String contNo = params.getContNo();
        String dvcNo = params.getDvcNo();
        Long creator = params.getCreator();
        if (StringUtils.isNull(contNo)) {
            throw new WmsException("send_wcs_error_002", "容器条码不能为空");
        }
        // 起始位置与目的地
        String trkType = params.getTrkType();
        String frmPos = params.getFrmPos();
        String toPos = params.getToPos();
        if (StringUtils.isEmpty(trkType)) {
            throw new WmsException("send_wcs_error_003", "任务类型不能为空");
        }
        if (StringUtils.isEmpty(frmPos)) {
            throw new WmsException("send_wcs_error_004", "起始位置不能为空");
        }
        if (StringUtils.isEmpty(toPos)) {
            throw new WmsException("send_wcs_error_005", "目的地不能为空");
        }
        // 2.检查LPN是否存在未下发的任务
        QueryWrapper<WcsTaskEntity> contNoQw = new QueryWrapper<>();
        contNoQw.lambda().eq(WcsTaskEntity::getContNo, contNo)
                .lt(WcsTaskEntity::getTrkStatus, WmsConstants.TASK_STATUS_DONE);
        Long taskCont = wcsTaskMapper.selectCount(contNoQw);
        if (taskCont > 0) {
            // 如果托盘已存在搬送任务如何处理
            throw new WmsException("容器【" + contNo + "】已存在搬送任务!");
        }
        // 3.写入数据库
        WcsTaskEntity wcsTrk = new WcsTaskEntity();
        // 生成唯一主键
        wcsTrk.setRequestPk(Seq.getId());
        wcsTrk.setContNo(contNo);
        wcsTrk.setContType(params.getContType());
        wcsTrk.setTrkType(trkType);
        wcsTrk.setDvcNo(dvcNo);
        wcsTrk.setFrmPos(frmPos);
        wcsTrk.setToPos(toPos);
        wcsTrk.setTrkPrty(params.getTrkPrty());
        wcsTrk.setCreator(creator);
        // 返回成功写入的任务ID
        return ProcResult.success("成功下发设备任务【" + contNo + "】");
    }
}
